package com.bnlr.lrparking.adapter;

import android.animation.Keyframe;
import android.animation.ObjectAnimator;
import android.animation.PropertyValuesHolder;
import android.content.Context;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.CheckedTextView;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bnlr.lrparking.constant.Urls;
import com.bumptech.glide.Glide;
import com.bnlr.lrparking.app.Application;
import com.bnlr.lrparking.R;
import com.bnlr.lrparking.appui.stall.InvestActivity;
import com.bnlr.lrparking.app.AppConfig;
import com.bnlr.lrparking.model.StallData;
import com.bnlr.lrparking.model.StallM;
import com.bnlr.lrparking.constant.LrConstant;
import com.bnlr.lrparking.view.CarCommon;
import com.bnlr.nohttp.CallServer;
import com.bnlr.nohttp.CustomHttpListener;
import com.yolanda.nohttp.NoHttp;
import com.yolanda.nohttp.rest.Request;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by rr on 2016/7/2.
 */
public class StallAdapter extends BaseAdapter {

    public Request<String> mRequest;
    private Context mcontext;
    private List<StallData> list=new ArrayList<>();
    private LayoutInflater inflater;
    CarCommon common = new CarCommon();


    public StallAdapter(Context context, List<StallData> list) {
        super();
        this.mcontext = context;
        this.list = list;
        inflater = LayoutInflater.from(mcontext);
    }

    @Override
    public int getCount() {
        if (list != null) {
            return list.size();
        }
        return 0;
    }

    @Override
    public Object getItem(int i) {
        return null;
    }

    @Override
    public long getItemId(int i) {
        return 0;
    }

    @Override
    public View getView(int i, View convertView, ViewGroup viewGroup) {
        final ViewHoder hoder;
        if (convertView == null) {
            hoder = new ViewHoder();
            convertView = inflater.inflate(R.layout.item_stall, null);
            hoder.img_stall=(ImageView)convertView.findViewById(R.id.img_stall);
            hoder.rely_goinvest=(RelativeLayout)convertView.findViewById(R.id.rely_goinvest);
            hoder.stall_phone=(RelativeLayout)convertView.findViewById(R.id.stall_phone);
            hoder.rely_college=(RelativeLayout)convertView.findViewById(R.id.rely_college);
            hoder.tv_stall_type = (TextView) convertView.findViewById(R.id.tv_stall_type);
            hoder.tv_stall_name=(TextView) convertView.findViewById(R.id.tv_stall_name);
            hoder.tv_stall_number = (TextView) convertView.findViewById(R.id.tv_stall_number);
            hoder.tv_stall_time=(TextView) convertView.findViewById(R.id.tv_stall_time);
            hoder.tv_stall_num = (TextView) convertView.findViewById(R.id.tv_stall_num);
            hoder.tv_stall_earnin_num=(TextView) convertView.findViewById(R.id.tv_stall_earnin_num);
            hoder.checkBox_college=(CheckedTextView)convertView.findViewById(R.id.checkBox_college);
            convertView.setTag(hoder);
        } else {
            hoder = (ViewHoder) convertView.getTag();
        }
        final StallData bean = list.get(i);
        Glide.with(mcontext)
                .load(bean.getParkPhoto())
                .placeholder(R.mipmap.img_stall_error)
                .error(R.mipmap.img_stall_error)
                .into(hoder.img_stall);
        hoder.tv_stall_type.setText(bean.getOwnerType());
        hoder.tv_stall_name.setText(bean.getParkName());
        hoder.tv_stall_number.setText("车位编号："+bean.getNumber());
        hoder.tv_stall_time.setText("投资时间："+bean.getBeginTime()+"-"+bean.getEndTime());
        hoder.tv_stall_num.setText(""+bean.getSellingPrice());
        hoder.tv_stall_earnin_num.setText(""+bean.getIncomeRockon());

        if (bean.getIsFavorite().equals("0")){
            hoder.checkBox_college.setChecked(false);
        }else if (bean.getIsFavorite().equals("1")){
            hoder.checkBox_college.setChecked(true);
        }

        hoder.rely_goinvest.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent=new Intent(mcontext,InvestActivity.class);
                intent.putExtra("monthCount",bean.getMonthCount());
                intent.putExtra("number",bean.getNumber());//
                intent.putExtra("id",bean.getId());
                intent.putExtra("sellingprice",bean.getSellingPrice());
                mcontext.startActivity(intent);
                AppConfig.getInstance().putString("isList", "0");//是从哪个列表去支付界面的
            }
        });
        hoder.stall_phone.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                common.phoneDialog(mcontext);
            }
        });
        hoder.rely_college.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startShakeByPropertyAnim(hoder.rely_college, 0.9f, 1.2f, 11f, 500);
                if (bean.getIsFavorite().equals("0")){
                    setCollege(bean.getIsFavorite(),"FavoriteSpace", bean.getId(),hoder.checkBox_college,bean);
                }else if (bean.getIsFavorite().equals("1")){
                    setCollege(bean.getIsFavorite(),"CancelFavoriteSpace", bean.getId(),hoder.checkBox_college,bean);
                }
            }
        });
        return convertView;
    }

    class ViewHoder {
        TextView tv_stall_type,tv_stall_name,tv_stall_number,tv_stall_time,tv_stall_num,tv_stall_earnin_num;//
        ImageView img_stall;
        RelativeLayout rely_goinvest,stall_phone,rely_college;
        CheckedTextView checkBox_college;

    }

    //收藏的接口
    private void setCollege(final String is,final String FavoriteSpace, String id,final CheckedTextView checkedTextView,final StallData stallData){
        try {
            mRequest = NoHttp.createStringRequest(Urls.SPACE_IP, LrConstant.POST);
            /**
             * IsFavorite: 0是未收藏  1是已收藏
             * action: FavoriteSpace是从藏接口  CancelFavoriteSpace是取消收藏接口
             */
            mRequest.add("action", FavoriteSpace);
            mRequest.add("phonePara", Application.DEVICE_ID);
            mRequest.add("uid", AppConfig.getInstance().getString("uid", ""));
            mRequest.add("id", id);

            CallServer.getRequestInstance().add(mcontext, mRequest,
                    new CustomHttpListener<StallM>(mcontext, true, StallM.class) {
                        @Override
                        public void doWork(StallM data, String code) {
                            if ("1".equals(code)) {
                                if (is.equals("0")) {
                                    checkedTextView.setChecked(true);
                                    stallData.setIsFavorite("1");
                                } else if (is.equals("1")) {
                                    checkedTextView.setChecked(false);
                                    stallData.setIsFavorite("0");
                                }
                            }
                        }
                        @Override
                        public void onFinally(JSONObject obj, String code, boolean isSucceed) {
                            try {
                                super.onFinally(obj, code, isSucceed);
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        }
                    }, true);
        } catch (Exception e) {

        }
    }

    private void startShakeByPropertyAnim(View view, float scaleSmall, float scaleLarge, float shakeDegrees, long duration) {
        if (view == null) {
            return;
        }
        //TODO 验证参数的有效性

        //先变小后变大
        PropertyValuesHolder scaleXValuesHolder = PropertyValuesHolder.ofKeyframe(View.SCALE_X,
                Keyframe.ofFloat(0f, 1.0f),
                Keyframe.ofFloat(0.25f, scaleSmall),
                Keyframe.ofFloat(0.5f, scaleLarge),
                Keyframe.ofFloat(0.75f, scaleLarge),
                Keyframe.ofFloat(1.0f, 1.0f)
        );
        PropertyValuesHolder scaleYValuesHolder = PropertyValuesHolder.ofKeyframe(View.SCALE_Y,
                Keyframe.ofFloat(0f, 1.0f),
                Keyframe.ofFloat(0.25f, scaleSmall),
                Keyframe.ofFloat(0.5f, scaleLarge),
                Keyframe.ofFloat(0.75f, scaleLarge),
                Keyframe.ofFloat(1.0f, 1.0f)
        );

        ObjectAnimator objectAnimator = ObjectAnimator.ofPropertyValuesHolder(view, scaleXValuesHolder, scaleYValuesHolder, scaleYValuesHolder);
        objectAnimator.setDuration(duration);
        objectAnimator.start();
    }
}
